<?php
/**
 * CVerticalTableValidator class file.
 */

/**
 * Model validator for values in a vertical table
 * using a field as a reference of the validation rules
 * 
 * @author mfalero
 * @package Database
 */
class CVerticalTableValidator extends CValidator {
	public $ruleField  = 'datatype';
	
	public function validateAttribute($model, $attribute) {
		$rules = explode('|', $model->{$this->ruleField});
		
		if(!empty($rules[0])) {
			foreach ($rules as $rule) {
				$parts = array();
				
				if (!preg_match_all("/^([a-zA-Z]+)\s*(.*)/i", $rule, $parts)) {
					throw new Exception("Invalid datatype format: " . $rule);
				}
				
				$type = strtolower($parts[1][0]);
				$paramString = trim($parts[2][0]);
				
				$matches = array(); 
				$params = array();
				
				if(preg_match_all('/\(([a-zA-Z]*):([a-zA-Z0-9]+)[, ]*\)/i', $paramString, $matches)) {
					for($i = 0; $i < count($matches[0]); $i++) {
						//      keys                   values
						$params[$matches[1][$i]] = $matches[2][$i];
					}
				}
		
				CValidator::createValidator($type, $model, $attribute, $params)->validateAttribute($model, $attribute);
			}
		}
	}
}